package com.vogue.supplymall.order.domain.biz.impl;

import com.vogue.gear.memory.provider.IMemProvider;
import com.vogue.supplymall.common.constant.ConstantBean;
import com.vogue.supplymall.common.domain.dto.EditCartInfo;
import com.vogue.supplymall.common.domain.dto.OrderInfo;
import com.vogue.supplymall.common.domain.dto.RelevanceInfo;
import com.vogue.supplymall.common.domain.dto.SearchPrepayInfo;
import com.vogue.supplymall.common.domain.dto.UserInfo;
import com.vogue.supplymall.common.domain.tool.VestUtils;
import com.vogue.supplymall.order.common.CheckCartUtils;
import com.vogue.supplymall.order.common.OrderMemUtils;
import com.vogue.supplymall.order.domain.biz.CartBiz;
import com.vogue.supplymall.order.domain.biz.PrepaySearchBiz;
import com.vogue.supplymall.order.domain.model.Order;
import com.vogue.supplymall.order.domain.model.OrderBuyer;
import com.vogue.supplymall.order.domain.model.OrderItem;
import com.vogue.supplymall.order.domain.model.OrderItemProduct;
import com.vogue.supplymall.order.domain.service.OrderBuyerService;
import com.vogue.supplymall.order.domain.service.OrderItemProductService;
import com.vogue.supplymall.order.domain.service.OrderItemService;
import com.vogue.supplymall.order.domain.service.OrderService;
import com.vogue.supplymall.order.exception.AddCartException;
import com.vogue.supplymall.order.exception.AddOrderException;
import com.vogue.supplymall.order.exception.InsufficientInventoryException;
import com.vogue.supplymall.order.exception.OverMaxCountException;
import com.vogue.supplymall.order.exception.OverMaxProductCountException;
import com.vogue.supplymall.order.exception.AddCarItemCheckException;
import com.vogue.supplymall.shop.domain.model.ProductAttrplan;
import com.vogue.supplymall.shop.domain.service.ProductAttrplanService;
import com.vogue.supplymall.shop.domain.service.RelevanceService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * The type Cart biz.
 * 购物车service
 *
 * @aouthor: zhangliang
 * @date: Create in 2018-01-10
 */
@Service("cartBiz")
public class CartBizImpl implements CartBiz {
    /**
     * The constant LOGGER_CARTBIZIMPL.
     */
    public static final Logger LOGGER_CARTBIZIMPL = LoggerFactory.getLogger(CartBizImpl.class);

    @Resource
    private OrderService orderService;
    @Resource
    private OrderItemService orderItemService;
    @Resource
    private OrderItemProductService orderItemProductService;
    @Resource
    private OrderBuyerService orderBuyerService;
    @Resource
    private ProductAttrplanService productAttrplanService;
    @Resource
    private OrderMemUtils orderMemUtils;
    @Resource(name = "memProvider")
    private IMemProvider<Object> memProvider;
    @Resource
    private RelevanceService relevanceService;
    @Resource
    private PrepaySearchBiz prepaySearchBiz;
    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public Map<String, Object> findCart(EditCartInfo editCartInfo, UserInfo userInfo) {
        Map<String, String> invalidPid = new HashMap<>();
        List<Map<String, Object>> result = orderItemProductService.findCart(editCartInfo);
        LOGGER_CARTBIZIMPL.info("findCart >> result.size : " + result.size());
        // 失效商品
        List<Map<String, Object>> invalid = result.parallelStream()
                .filter((map) -> CheckCartUtils.checkInvalid(invalidPid, map))
                .collect(Collectors.toList());
        // 有效店铺
        List<Map<String, Object>> goods = result.parallelStream()
                .filter((map) -> CheckCartUtils.checkValid(invalidPid, map))
                .collect(Collectors.toList());

        Comparator<Map<String, Object>> comparator = (m1, m2) -> {
            try {
                return format.parse(m2.get("createdate").toString()).compareTo(format.parse(m1.get("createdate").toString()));
            } catch (ParseException e) {
                return 0;
            }
        };

        List<Map<Object, Object>> valids = new ArrayList<>();
        // 2018/10/29 查询预付款余额
        SearchPrepayInfo searchPrepayInfo = new SearchPrepayInfo();
        searchPrepayInfo.setSyscodeid(userInfo.getSyscodeid());
        searchPrepayInfo.setOrganid(userInfo.getOrganInfo().getId());
        // 将店铺分组--此处必须为有序map
        LinkedHashMap<Object, Object> group = new LinkedHashMap<>();
        goods.stream().forEach((map) -> group.put(map.get("sid"), ""));
        group.forEach((key, value) -> {
            List<Map<String, Object>> valid = new ArrayList<>();
            Map<Object, Object> goodsData = new HashMap<>();
            goods.stream().forEach((good) -> {
                if (key.equals(good.get("sid"))) {
                    valid.add(good);
                    goodsData.put("id", good.get("sid"));
                    goodsData.put("shopName", good.get("sname"));
                    goodsData.put("groupName", good.get("entname"));
                    // 2018/10/29 查询预付款余额
                    searchPrepayInfo.setSellorganid(new Long(good.get("organid").toString()));
                    searchPrepayInfo.setSellsyscodeid(new Long(good.get("syscodeid").toString()));
                    Map<String, String> prepay = prepaySearchBiz.searchPrepayBalance(searchPrepayInfo);
                    goodsData.put("paymode", prepay.get("paymode"));
                }
            });
//            valid.sort(comparator);
            goodsData.put("goodsData", valid);
            valids.add(goodsData);
        });
        Map<String, Object> cart = new HashMap<>();
        cart.put("valid", valids);
        cart.put("invalid", invalid);
        /* 将用户购物车信息存入缓存 */
//        orderMemUtils.setCartCache(cart, result.size(), editCartInfo);
        // 0:单笔 1:合并
        cart.put("payTogether", VestUtils.getPayTogether());
        return cart;
    }


    @Override
    @Transactional
    public void addCart(EditCartInfo editCartInfo, UserInfo info) {
        /*check库存数*/
        checkInventory(editCartInfo);
        /*检索用户是否有购物车*/
        Optional<Long> orderId = checkCartIsExist(editCartInfo);
        // 如果该用户有购物车则更新或增加一个购物车项目
        if (orderId.isPresent()) {
            editCartInfo.setOrderId(orderId.get());
            Optional itemID = addCartItem(editCartInfo, info);
        } else {
            // 该用户没有购物车则为用户，创建一个新购物车
            Optional<Long> orderID = addNewCart(editCartInfo, info);
        }
    }

    /**
     * 添加一个新的购物车
     * 包括订单、订单项目、订单买家、订单项目商品
     *
     * @param editCartInfo
     * @return
     */
    private Optional<Long> addNewCart(EditCartInfo editCartInfo, UserInfo userInfo) {
        // add order -- 购物车没有订单状态，不会create订单状态信息
        Order order = new Order();
        order.setSyscodeid(editCartInfo.getSyscodeid());
        order.setOrdernumber("0");
        order.setCommitflag(0);
        order.setTotalprice(BigDecimal.ZERO);
        order.setTotalquantity(0);
        order.setMemo("");
        order.setFreight(BigDecimal.ZERO);
        order.setAdjustprice(BigDecimal.ZERO);
        order.setIsInvoice(false);
        order.setFinalprice(BigDecimal.ZERO);
        orderService.addOrder(order);
        // add orderBuyer
        OrderBuyer buyer = new OrderBuyer();
        buyer.setUserid(editCartInfo.getLoginId());
        buyer.setSyscodeid(editCartInfo.getSyscodeid());
        if (null != editCartInfo.getOrganid()) {
            buyer.setOrganid(editCartInfo.getOrganid());
        } else {
            buyer.setOrganid(0L);
        }
        if (null != userInfo.getOrganInfo()) {
            /*2018-2-28添加matchid*/
            buyer.setMatchid(userInfo.getOrganInfo().getMatchid());
        } else {
            buyer.setMatchid(editCartInfo.getLoginId().toString());
        }
        buyer.setOrderid(order.getId());
        buyer.setBtel(editCartInfo.getTel());
        buyer.setBuyeraddress("");
        buyer.setBuyername("");
        buyer.setBuyertype(userInfo.getOrganInfo() == null ? 0 : 1);
        buyer.setEntname("");
        buyer.setStorename("");
        buyer.setSyscode(userInfo.getSyscode());
        orderBuyerService.addOrderBuyer(buyer);
        // add orderItem
        OrderItem orderItem = new OrderItem();
        orderItem.setOrderid(order.getId());
        orderItem.setItemquantity(editCartInfo.getItemQuantity());
        if (null != editCartInfo.getStorageId()) {
            orderItem.setStorageId(editCartInfo.getStorageId());
        } else {
            orderItem.setStorageId(0L);
        }

        if (StringUtils.isNotEmpty(editCartInfo.getStorage())) {
            orderItem.setStorage(editCartInfo.getStorage());
        } else {
            orderItem.setStorage("");
        }

        if (StringUtils.isNotEmpty(editCartInfo.getB_matchid())) {
            /*2018-2-28添加matchid*/
            orderItem.setMatchid(editCartInfo.getB_matchid());
        } else {
            orderItem.setMatchid("");
        }
        orderItem.setItemprice(BigDecimal.ZERO);
        /* add 2018/7/26 发货数量 发货金额 差异数量 差异金额 */
        BigDecimal qty = new BigDecimal(editCartInfo.getItemQuantity());
        orderItem.setSendcount(qty);
        orderItem.setSendmoney(BigDecimal.ZERO);
        orderItem.setDiffcount(BigDecimal.ZERO);
        orderItem.setDiffmoney(BigDecimal.ZERO);
        orderItemService.addOrderItem(orderItem);
        // add orderItemProduct
        OrderItemProduct itemProduct = new OrderItemProduct();
        itemProduct.setOrderid(order.getId());
        itemProduct.setOrderitemid(orderItem.getId());
        itemProduct.setProductid(editCartInfo.getProductId());
        itemProduct.setAttrplanid(editCartInfo.getAttrplanid());
        itemProduct.setImgurl("");
        itemProduct.setPname("");
        itemProduct.setPrice(BigDecimal.ZERO);
        itemProduct.setPunit("");
        itemProduct.setWeight(BigDecimal.ZERO);
        itemProduct.setPmatchid("");
        itemProduct.setUmatchid("");
        itemProduct.setItemquantity(editCartInfo.getItemQuantity());
        itemProduct.setMainproductflag(true);
        orderItemProductService.addOrderItemProduct(itemProduct);
        return Optional.of(order.getId());
    }

    private void checkInventory(EditCartInfo editCartInfo) {
        ProductAttrplan productAttrplan = productAttrplanService.get(editCartInfo.getAttrplanid());
        if (null == productAttrplan) {
            throw new AddOrderException("");
        }

        if (productAttrplan.getInventory().compareTo(new BigDecimal(editCartInfo.getItemQuantity().toString())) < 0) {
            throw new InsufficientInventoryException("");
        }
    }

    /**
     * 检索用户是否有购物车
     *
     * @param editCartInfo
     * @return Optional
     */
    private Optional<Long> checkCartIsExist(EditCartInfo editCartInfo) {
        OrderBuyer buyer = new OrderBuyer();
        if (null != editCartInfo.getOrganid()) {
            buyer.setOrganid(editCartInfo.getOrganid());
        } else {
            buyer.setOrganid(0L);
        }
        buyer.setSyscodeid(editCartInfo.getSyscodeid());
        buyer.setUserid(editCartInfo.getLoginId());
        OrderBuyer result = orderBuyerService.getOrderBuyerBySql(buyer);
        if (null != result) {
            // 如果存在买家的购物车则返回一个购物车id
            return Optional.of(result.getOrderid());
        }
        return Optional.empty();
    }

    /**
     * 用户已经有购物车的场合，
     * 添加/更新一个购物车项目，
     * 如果已有该规格的商品则商品数量+1，
     * 如果没有该规格的商品则增加一个购物车项目。（去掉）
     *  modify in 2018/2/11: 如果所选仓库不同也为购物车增加一个项目。
     *  modify in 2018/11/14: 同一库房下不同规格的商品不能加入购物车
     *
     * @param editCartInfo
     * @return 返回itemID
     */
    private Optional addCartItem(EditCartInfo editCartInfo, UserInfo info) {
        if (!checkCartItemMax(editCartInfo.getOrderId())) {
            throw new OverMaxCountException("");
        }
        //检查加入购物车的（商品+库房）是否存在购物车中存在---也就是同一库房下不同规格的商品不能加入购物车
        if (checkCartItemAndStorageIsExist(editCartInfo)){
            throw new AddCarItemCheckException("购物车已经有该商品了，请添加相同规格的");
        }
        /*查看item是否存在*/
        Optional<Long> orderItemId = checkCartItemIsExist(editCartInfo, info);
        // 购物车中已经有该商品并且仓库相同，则更新商品数量
        if (orderItemId.isPresent()) {
            OrderItem orderItem = orderItemService.get(orderItemId.get());
            if (null != orderItem) {
                orderItem.setItemquantity(orderItem.getItemquantity() + editCartInfo.getItemQuantity());
            } else {
                throw new RuntimeException("");
            }
            if (orderItem.getItemquantity() > ConstantBean.MAX_PRODUCT_COUNT) {
                throw new OverMaxProductCountException(ConstantBean.MAX_PRODUCT_COUNT.toString());
            }
            orderItem.setModifyDate(new Date());
            /* add 2018/7/26 发货数量 发货金额 差异数量 差异金额 */
            BigDecimal qty = new BigDecimal(orderItem.getItemquantity());
            orderItem.setSendcount(qty);
            orderItem.setDiffcount(BigDecimal.ZERO);
            orderItemService.update(orderItem);
        } else {
            // 购物车中没有该商品或者仓库不同，为购物车添加一个项目和项目所属商品
            // 添加一个购物车项目
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderid(editCartInfo.getOrderId());
            orderItem.setItemprice(BigDecimal.ZERO);
            orderItem.setItemquantity(editCartInfo.getItemQuantity());
            if (null != editCartInfo.getStorageId()) {
                orderItem.setStorageId(editCartInfo.getStorageId());
            } else {
                orderItem.setStorageId(0L);
            }

            if (StringUtils.isNotEmpty(editCartInfo.getStorage())) {
                orderItem.setStorage(editCartInfo.getStorage());
            } else {
                orderItem.setStorage("");
            }
            if (StringUtils.isNotEmpty(editCartInfo.getB_matchid())) {
                /*2018-2-28添加matchid*/
                orderItem.setMatchid(editCartInfo.getB_matchid());
            } else {
                orderItem.setMatchid("");
            }
            /* add 2018/7/26 发货数量 发货金额 差异数量 差异金额 */
            BigDecimal qty = new BigDecimal(editCartInfo.getItemQuantity());
            if (orderItem.getItemquantity() > ConstantBean.MAX_PRODUCT_COUNT) {
                throw new OverMaxProductCountException(ConstantBean.MAX_PRODUCT_COUNT.toString());
            }
            orderItem.setSendcount(qty);
            orderItem.setSendmoney(BigDecimal.ZERO);
            orderItem.setDiffcount(BigDecimal.ZERO);
            orderItem.setDiffmoney(BigDecimal.ZERO);
            OrderItem result = orderItemService.addOrderItem(orderItem);
            // 添加一个商品
            if (null != result) {
                OrderItemProduct orderItemProduct = new OrderItemProduct();
                orderItemProduct.setOrderid(editCartInfo.getOrderId());
                orderItemProduct.setProductid(editCartInfo.getProductId());
                orderItemProduct.setOrderitemid(result.getId());
                orderItemProduct.setAttrplanid(editCartInfo.getAttrplanid());
                orderItemProduct.setPrice(BigDecimal.ZERO);
                orderItemProduct.setPunit("");
                orderItemProduct.setPname("");
                orderItemProduct.setImgurl("");
                orderItemProduct.setWeight(BigDecimal.ZERO);
                orderItemProduct.setPmatchid("");
                orderItemProduct.setUmatchid("");
                orderItemProduct.setItemquantity(editCartInfo.getItemQuantity());
                orderItemProduct.setMainproductflag(true);
                orderItemProductService.addOrderItemProduct(orderItemProduct);
            }
        }
        return orderItemId;

    }

    /**
     * 检索购物车项目中是否有该商品
     *
     * @param editCartInfo
     * @return Optional
     */
    private Optional<Long> checkCartItemIsExist(EditCartInfo editCartInfo, UserInfo info) {
        /*查找购物车项目的商品--根据商品计划和仓库*/
        OrderItemProduct result = new OrderItemProduct();
        if (null == editCartInfo.getStorageId()) {
            result = orderItemProductService.getOrderItemProductBySql(editCartInfo.getOrderId(), editCartInfo.getProductId(), editCartInfo.getAttrplanid(), 0L);
        } else {
            result = orderItemProductService.getOrderItemProductBySql(editCartInfo.getOrderId(), editCartInfo.getProductId(), editCartInfo.getAttrplanid(), editCartInfo.getStorageId());
        }

        if (null != result) {
            // 如果是个人直接返回购物车项目id
            return Optional.of(result.getOrderitemid());
        }
        return Optional.empty();
    }

    /**
     * 查看购物车项目的数量
     *
     * @param orderId
     * @return Optional
     */
    private Boolean checkCartItemMax(Long orderId) {
        OrderItem orderItem = new OrderItem();
        orderItem.setOrderid(orderId);
        Long count = orderItemService.getOrderItemCount(orderItem);
        // 如果超过购物车最大数量则返回false
        return null == count || ConstantBean.ORDER_CART_MAX_COUNT.compareTo(count) > 0;
    }

    @Override
    @Transactional
    public void updateCart(EditCartInfo editCartInfo) {
        ProductAttrplan attrplan = productAttrplanService.get(editCartInfo.getAttrplanid());
        if (null == attrplan) throw new InsufficientInventoryException("");
        if (attrplan.getInventory().compareTo(new BigDecimal(editCartInfo.getItemQuantity().toString())) < 0) {
            throw new InsufficientInventoryException("");
        }
        String sql = " orderid = #{orderid} and id = #{id}";
        Map<String, Object> para = new HashMap<>();
        para.put("orderid", editCartInfo.getOrderId());
        para.put("id", editCartInfo.getOrderItemId());
        // 更新
        OrderItem orderItem = orderItemService.selectOneByWhr0(sql, para);
        if (null != orderItem) {
            if (null != editCartInfo.getStorageId()) {
                orderItem.setStorageId(editCartInfo.getStorageId());
            } else {
                orderItem.setStorageId(0L);
            }

            if (StringUtils.isNotEmpty(editCartInfo.getStorage())) {
                orderItem.setStorage(editCartInfo.getStorage());
            } else {
                orderItem.setStorage("");
            }
            if (StringUtils.isNotEmpty(editCartInfo.getB_matchid())) {
                /*2018-2-28添加matchid*/
                orderItem.setMatchid(editCartInfo.getB_matchid());
            } else {
                orderItem.setMatchid("");
            }
            orderItem.setItemquantity(editCartInfo.getItemQuantity());
            orderItem.setModifyDate(new Date());
            /* add 2018/7/26 发货数量 发货金额 差异数量 差异金额 */
            BigDecimal qty = new BigDecimal(editCartInfo.getItemQuantity());
            orderItem.setSendcount(qty);
            orderItem.setDiffcount(BigDecimal.ZERO);
            orderItemService.update(orderItem);
        } else {
            throw new RuntimeException("");
        }
    }

    @Override
    @Transactional
    public void updateCartList(List<EditCartInfo> editCartInfoList) {
        for (EditCartInfo editCartInfo : editCartInfoList) {
            updateCart(editCartInfo);
        }
    }

    @Override
    @Transactional
    public void removeCart(EditCartInfo editCartInfo) {
        List<Map<String, Object>> removeId = editCartInfo.getRemoveId();
        if (removeId.size() > 0) {
            for (Map<String, Object> map : removeId) {
                // modify 2018/4/8 为避免用户数据丢失，修改删除购物车为更新。
                /*删除订单项目*/
                OrderItem orderItem = orderItemService.get(Long.valueOf(map.get("oiid").toString()));
                orderItem.setDisabledflag(true);
                orderItem.setModifyDate(new Date());
                orderItemService.update(orderItem);
                /*删除订单项目的商品*/
                OrderItemProduct itemProduct = orderItemProductService.get(Long.valueOf(map.get("oipid").toString()));
                itemProduct.setDisabledflag(true);
                itemProduct.setModifyDate(new Date());
                orderItemProductService.update(itemProduct);
            }
        }
    }


    @Override
    @Transactional
    public void cartMoveWatch(EditCartInfo editCartInfo, UserInfo info) {
        /*删除购物车商品*/
        this.removeCart(editCartInfo);
        /*添加关注*/
        RelevanceInfo relevanceInfo = new RelevanceInfo();
        relevanceInfo.setType(1);
        relevanceInfo.setTargetObjType(2);
        relevanceInfo.setUserId(info.getLoginId());
        relevanceInfo.setTargetName(editCartInfo.getPname());
        relevanceInfo.setTargetObjId(editCartInfo.getProductId());
        relevanceService.addRelevance(relevanceInfo);
    }

    @Override
    @Transactional
    public void againAddCart(OrderInfo orderInfo, UserInfo userInfo) {
        LOGGER_CARTBIZIMPL.info(" >>> 再次加入购物车 stsrt");
        /*查询订单买家*/
        OrderBuyer buyer = new OrderBuyer();
        buyer.setSyscodeid(userInfo.getSyscodeid());
        buyer.setUserid(userInfo.getLoginId());
        if (null != userInfo.getOrganInfo()) {
            buyer.setOrganid(userInfo.getOrganInfo().getId());
        } else {
            buyer.setOrganid(0L);
        }
        buyer = orderBuyerService.searchOrderBuyerBySql(buyer);
        if (null == buyer) {
            /*没有查询到订单买家*/
            throw new AddCartException("");
        }
        if (!checkCartItemMax(buyer.getOrderid())) {
            /*超出最大购物车数量*/
            throw new OverMaxCountException("");
        }

        final Long orderId = buyer.getOrderid();

        for (Map<String, Object> map : orderInfo.getGoodsData()) {
            Long productid = new Long(map.get("productid").toString());
            Long attrplanid = new Long(map.get("attrplanid").toString());
            Long storageid = new Long(map.get("storageid").toString());

            //检查加入购物车的（商品+库房）是否存在购物车中存在---也就是同一库房下不同规格的商品不能加入购物车
            EditCartInfo editCartInfo = new EditCartInfo();
            editCartInfo.setLoginId(userInfo.getLoginId());
            editCartInfo.setOrganid(buyer.getOrganid());
            editCartInfo.setSyscodeid(userInfo.getSyscodeid());
            editCartInfo.setProductId(productid);
            editCartInfo.setAttrplanid(attrplanid);
            editCartInfo.setStorageId(storageid);
            if (checkCartItemAndStorageIsExist(editCartInfo)){
                throw new AddCarItemCheckException("购物车已经有该商品了，请添加相同规格的");
            }

            OrderItemProduct result = new OrderItemProduct();
            if (null == userInfo.getOrganInfo()) {
                LOGGER_CARTBIZIMPL.error(" 没有默认机构 ");
                result = orderItemProductService.getOrderItemProductBySql(orderId, productid, attrplanid, 0L);
            } else {
                result = orderItemProductService.getOrderItemProductBySql(orderId, productid, attrplanid, storageid);
            }

            if (null != result) {
                /*已有同仓库商品，更新商品数量*/
                OrderItem orderItem = orderItemService.get(result.getOrderitemid());
                orderItem.setItemquantity(new Integer(map.get("itemquantity").toString()) + orderItem.getItemquantity());
                orderItem.setModifyDate(new Date());
                /* add 2018/7/26 发货数量 发货金额 差异数量 差异金额 */
                BigDecimal qty = new BigDecimal(orderItem.getItemquantity());
                orderItem.setSendcount(qty);
                orderItem.setDiffcount(BigDecimal.ZERO);
                orderItemService.update(orderItem);
                LOGGER_CARTBIZIMPL.info(" >>> 已有同仓库商品，更新商品数量");
            } else {
                /*没有同仓库商品，添加商品项目*/
                OrderItem orderItem = orderItemService.get(new Long(map.get("oiid").toString()));
                orderItem.setOrderid(orderId);
                orderItem.setId(null);
                orderItem.setCreateDate(new Date());
                if (1 == orderInfo.getAgainBuyFlag()) {
                    orderItem.setItemquantity(1);
                }
                orderItem.setModifyDate(new Date());
                /* add 2018/7/26 发货数量 发货金额 差异数量 差异金额 */
                BigDecimal qty = new BigDecimal(orderItem.getItemquantity());
                orderItem.setSendcount(qty);
                orderItem.setDiffcount(BigDecimal.ZERO);
                orderItemService.save(orderItem);
                LOGGER_CARTBIZIMPL.info(" >>> 没有同仓库商品，添加商品项目 1:添加购物车项目");
                OrderItemProduct orderItemProduct = orderItemProductService.get(new Long(map.get("oipid").toString()));
                orderItemProduct.setId(null);
                orderItemProduct.setOrderitemid(orderItem.getId());
                orderItemProduct.setOrderid(orderId);
                orderItemProduct.setCreateDate(new Date());
                orderItemProduct.setModifyDate(new Date());
                if (1 == orderInfo.getAgainBuyFlag()) {
                    orderItemProduct.setItemquantity(1);
                }
                //orderItemProduct.setItemquantity(new Integer(map.get("itemquantity").toString()) + orderItemProduct.getItemquantity());
                orderItemProduct.setMainproductflag(true);
                orderItemProductService.save(orderItemProduct);
                LOGGER_CARTBIZIMPL.info(" >>> 没有同仓库商品，添加商品项目 2:添加购物车项目的商品");
            }
        }
    }

    @Override
    public Map<String, Object> findCartCount(EditCartInfo editCartInfo) {
        Long count = orderItemProductService.findCartCount(editCartInfo);
        LOGGER_CARTBIZIMPL.info("findCartCount >> result.size : " + count);
        Map<String, Object> cartCount = new HashMap<>();
        cartCount.put("carCount", count);
        return cartCount;
    }

    /**
     * 检索购物车项目中是否有该（商品+仓库）
     * @param editCartInfo
     * @return Boolean
     */
    public Boolean checkCartItemAndStorageIsExist(EditCartInfo editCartInfo) {
        Long count = orderItemProductService.getItemAndStorage(editCartInfo);
        LOGGER_CARTBIZIMPL.info("getItemAndStorage >> result.size : " + count);
        if (count > 0L) {
            return true;
        }
        return false;
    }


}
